<template>
    <div>
        <div class="e-table">
            <div class="mainTitle">
                <i class="el-icon-d-arrow-right"></i>暂扣保证金
            </div>
            <div class="top" v-if="!isRedSingle && !isDtl">
                <div class="left">
                    <div>
                        <el-button
                            size="mini"
                            class="btn-blue"
                            @click="suspendedAdd"
                            >新增</el-button
                        >
                        <el-button
                            size="small"
                            class="btn-delete"
                            @click="suspendedClick"
                            >批量删除</el-button
                        >
                    </div>
                    <!-- <div class="batchBox" @click="batchOperation('suspended')">
                        <img class="batchicon" src="@/assets/piliang.png" />
                        <span class="batchfont">{{ isBatch[0].batch }}</span>
                    </div> -->
                </div>
            </div>

            <el-table
                :data="suspendedData"
                border
                style="width: 100%"
                ref="suspendedTable"
                :row-class-name="tableRowClassNamezk"
                @selection-change="suspendedSelect"
                :max-height="$store.state.tableHeight"
                v-sortTable="{ 'tableData': suspendedData, '_this': this, 'ref': 'suspendedTable' }"
            >
                <el-table-column
                    type="selection"
                    width="55"
                    v-if="!isRedSingle && !isDtl"
                >
                </el-table-column>
                <el-table-column
                    label="操作"
                    fixed
                    align="center"
                    v-if="!isRedSingle && !isDtl"
                >
                    <template slot-scope="{ row, $index }">
                        <div class="handle">
                            <div style="cursor: pointer" class="list_box">
                                <img
                                    src="@/assets/btn/delete.png"
                                    class="add_sub"
                                    title='删除'
                                    @click="suspendedDelete(row, $index)"
                                />
                            </div>
                        </div>
                    </template>
                </el-table-column>
                <el-table-column
                    prop="withholdBondName"
                    label="名称"
                    min-width="100"
                >
                </el-table-column>
                <el-table-column
                    prop="withholdBond"
                    label="暂扣保证金(元)"
                    width="200"
                >
                    <template v-slot="{ row }">
                        <el-input
                            v-model="row.withholdBond"
                            v-enter-float="{
                                set: row,
                                key: 'withholdBond'
                            }"
                            placeholder=""
                            @blur="withholdBondBlur(row)"
                            v-if="!isRedSingle && !isDtl"
                        ></el-input>
                        <span v-else>{{ row.withholdBond }}</span>
                    </template>
                </el-table-column>
                <el-table-column
                    prop="lastPeriodWithholdBond"
                    label="截止上期末暂扣保证金(元)"
                    width="200"
                >
                </el-table-column>
                <el-table-column
                    prop="withholdExplain"
                    label="说明"
                    min-width="100"
                >
                    <template v-slot="{ row }">
                        <el-input
                            v-model="row.withholdExplain"
                            placeholder=""
                            @blur="withholdBondBlur(row)"
                            v-if="!isRedSingle && !isDtl"
                            type="textarea"
                            :rows="2"
                            resize="none"
                            maxlength="200"
                        ></el-input>
                        <span v-else>{{ row.withholdExplain }}</span>
                    </template>
                </el-table-column>
            </el-table>
        </div>

        <div class="e-table">
            <div class="mainTitle">
                <i class="el-icon-d-arrow-right"></i>返还保证金
            </div>
            <div class="top" v-if="!isRedSingle && !isDtl">
                <div class="left">
                    <div>
                        <el-button
                            size="mini"
                            class="btn-blue"
                            @click="returnAdd"
                            >新增</el-button
                        >
                        <el-button
                            size="small"
                            class="btn-delete"
                            @click="returnClick"
                            >批量删除</el-button
                        >
                    </div>
                    <!-- <div class="batchBox" @click="batchOperation('return')">
                        <img class="batchicon" src="@/assets/piliang.png" />
                        <span class="batchfont">{{ isBatch[1].batch }}</span>
                    </div> -->
                </div>
            </div>

            <el-table
                :data="returnData"
                border
                style="width: 100%"
                ref="returnTable"
                :row-class-name="tableRowClassNamefh"
                @selection-change="returnSelect"
                :max-height="$store.state.tableHeight"
                v-sortTable="{ 'tableData': returnData, '_this': this, 'ref': 'returnTable' }"
            >
                <el-table-column
                    type="selection"
                    width="55"
                    v-if="!isRedSingle && !isDtl"
                >
                </el-table-column>
                <el-table-column
                    label="操作"
                    fixed
                    align="center"
                    v-if="!isRedSingle && !isDtl"
                >
                    <template slot-scope="{ row, $index }">
                        <div class="handle">
                            <div style="cursor: pointer" class="list_box">
                                <img
                                    src="@/assets/btn/delete.png"
                                    class="add_sub"
                                    title='删除'
                                    @click="returnDelete(row, $index)"
                                />
                            </div>
                        </div>
                    </template>
                </el-table-column>
                <el-table-column
                    prop="returnBondName"
                    label="名称"
                    min-width="100"
                >
                </el-table-column>
                <el-table-column
                    prop="returnBond"
                    label="返还保证金(元)"
                    width="200"
                >
                    <template v-slot="{ row }">
                        <el-input
                            v-model="row.returnBond"
                            v-enter-float="{
                                set: row,
                                key: 'returnBond'
                            }"
                            placeholder=""
                            @blur="returnBondBlur(row)"
                            v-if="!isRedSingle && !isDtl"
                        ></el-input>
                        <span v-else>{{ row.returnBond }}</span>
                    </template>
                </el-table-column>
                <el-table-column
                    prop="endNotReturnBond"
                    label="截止本期末未返还保证金(元)"
                    width="200"
                >
                </el-table-column>
                <el-table-column
                    prop="returnExplain"
                    label="说明"
                    min-width="100"
                >
                    <template v-slot="{ row }">
                        <el-input
                            v-model="row.returnExplain"
                            placeholder=""
                            @blur="returnBondBlur(row)"
                            v-if="!isRedSingle && !isDtl"
                            type="textarea"
                            :rows="2"
                            resize="none"
                            maxlength="200"
                        ></el-input>
                        <span v-else>{{ row.returnExplain }}</span>
                    </template>
                </el-table-column>
            </el-table>
        </div>
    </div>
</template>

<script>
import { mapMutations } from 'vuex'
// import { openAppClient } from '@/utils/common'
import publics from '@/api/settlementManagement/equipmentBilling/public'
export default {
    props: {
        isRedSingle: {
            type: Boolean,
            require: false,
            default: false
        },
        billid: {
            type: String,
            require: false
        },
        number: {
            type: Object,
            require: false
        },
        isDtl: {
            // 是否查看页, 查看页不显示新增和删除按钮
            type: Boolean,
            require: false,
            default: false
        }
    },
    watch: {
        isRedSingle (nes, olds) {
            console.log(nes)
            console.log(olds)
        }
    },
    data () {
        return {
            suspendedData: [],
            returnData: [],
            contractIdszkbzj: [],
            contractIdsfhbzj: [],
            isBatch: [
                {
                    flag: false,
                    batch: '进入批量管理'
                },
                {
                    flag: false,
                    batch: '进入批量管理'
                }
            ],
            suspendedList: [], // 暂扣保证金复选框数据
            returnList: [] // 暂扣保证金复选框数据
        }
    },
    created () {
        this.getMargin()
    },
    methods: {
        ...mapMutations(['setSelectedInfo']),
        // 获取暂扣保证金/返还保证金的表格数据
        async getMargin () {
            let res = await publics.getMargin(this.billid)
            this.suspendedData = res.facilityBondList
            this.returnData = res.facilityReturnBondList
        },

        // 暂扣保证金新增
        async suspendedAdd () {
            if (this.suspendedData.length > 0) {
                this.suspendedData.forEach(item => {
                    if (item.changeType !== -1) {
                        this.contractIdszkbzj.push(item.contractId)
                    }
                })
            }

            // this.setSelectedInfo(this.number.type, this.contractIdszkbzj)
            // openAppClient('/showSelectedData', '传参')
            let res = await publics.suspendedAdd(
                this.number,
                this.contractIdszkbzj
            )
            if(res.length < 1) {
                this.suspendedData = this.suspendedData.filter((item, index) => {
                    if (item.bondId) {
                        this.$set(this.suspendedData[index], 'changeType', -1)
                    } else {
                        return false
                    }
                    return this.suspendedData
                })
            }
            // this.setSelectedInfo(res)
            // openAppClient('/showSelectedData', '结果')
            let arr = []
            arr = res.map(item => {
                return {
                    bondId: '', // 主键id
                    changeType: 1,
                    contractId: item.contractId, // 合同id
                    deductionRatio: item.deductionRatio, // 扣款比例
                    lastPeriodWithholdBond: item.lastPeriodWithholdBond, // 截止上期暂扣保证金
                    settleId: this.billid, // 结算id
                    withholdBond: item.withholdBond, // 暂扣保证金
                    withholdBondName: item.withholdBondName, // 暂扣保证金名称
                    withholdExplain: item.withholdExplain // 暂扣说明
                }
            })
            arr.forEach(item => {
                const isPush = this.suspendedData.every(
                    i => i.contractId !== item.contractId
                )
                if (isPush) {
                    this.suspendedData.push(item)
                } else {
                    const newArr = this.suspendedData.filter(
                        itm => itm.contractId === item.contractId
                    )
                    const indirectPush = newArr.some(m => m.changeType !== -1)
                    if (!indirectPush) {
                        this.suspendedData.push(item)
                    }
                }
            })
            this.suspendedData.forEach((item, index) => {
                let isExist = arr.every(it => item.contractId !== it.contractId)
                if (isExist) {
                    if (this.suspendedData[index]['bondId']) {
                        this.$set(this.suspendedData[index], 'changeType', -1)
                    }else {
                        this.suspendedData.splice(index, 1)
                    }
                }
            })
        },
        // 暂扣保证金/说明内容失去焦点时
        withholdBondBlur (row) {
            if (row.changeType === 1) {
                row.changeType = 1
            } else {
                row.changeType = 2
            }
        },
        // 暂扣保证金单条删除
        suspendedDelete (row, index) {
            this.clientPop('info', this.oneDeleteErr, () => {
                if (row.bondId) {
                    // 如果有明细id,说明是已经存在后端数据库中的数据,已存在的数据,在删除时只能将changType设为-1
                    this.$set(row, 'changeType', -1)
                } else {
                    // 没有明细id,说明是刚新增的数据,直接在原数组中删除即可
                    this.suspendedData.splice(index, 1)
                }
            })
        },
        tableRowClassNamezk ({ row }) {
            if (row.changeType === -1) {
                return 'warning-row'
            }
            return ''
        },
        // 是否进入批量操作
        batchOperation (name) {
            switch (name) {
            case 'suspended':
                this.isBatch[0].flag = !this.isBatch[0].flag
                if (this.isBatch[0].flag) {
                    this.isBatch[0].batch = '退出批量管理'
                    this.$refs.suspendedTable.clearSelection()
                } else {
                    this.isBatch[0].batch = '进入批量管理'
                }
                break
            case 'return':
                this.isBatch[1].flag = !this.isBatch[1].flag
                if (this.isBatch[1].flag) {
                    this.isBatch[1].batch = '退出批量管理'
                    this.$refs.returnTable.clearSelection()
                } else {
                    this.isBatch[1].batch = '进入批量管理'
                }
                break
            }
        },
        // 复选框选中的数据
        suspendedSelect (selection) {
            this.suspendedList = selection.filter(
                item => item.changeType !== -1
            )
        },
        // 点击批量删除
        suspendedClick () {
            const length = this.suspendedList.length
            if (length === 0) {
                this.clientPop('info', '你还未选择数据,请选择!')
            } else {
                this.clientPop(
                    'info',
                    this.moreDeleteErr(length),
                    this.suspendedDeleteList
                )
            }
        },
        // 批量删除
        suspendedDeleteList () {
            this.suspendedList.filter(row => {
                if (row.bondId) {
                    const index = this.suspendedData.findIndex(item => {
                        return item.bondId == row.bondId
                    })
                    this.$set(this.suspendedData[index], 'changeType', -1)
                } else {
                    this.suspendedData.forEach((item, index) => {
                        if (item.contractId === row.contractId) {
                            this.suspendedData.splice(index, 1)
                        }
                    })
                }
            })
            this.$refs.suspendedTable.clearSelection()
        },
        // --------------------返还保证金------------------------
        // 返还保证金新增
        async returnAdd () {
            if (this.returnData.length > 0) {
                this.returnData.forEach(item => {
                    if (item.changeType !== -1) {
                        this.contractIdsfhbzj.push(item.contractId)
                    }
                })
            }
            // this.setSelectedInfo(this.number, this.contractIdszkbzj)
            // openAppClient('/showSelectedData', '传参')
            let res = await publics.returnAdd(
                this.number,
                this.contractIdsfhbzj
            )
            if(res.length < 1) {
                this.returnData = this.returnData.filter((item, index) => {
                    if (item.bondId) {
                        this.$set(this.returnData[index], 'changeType', -1)
                    } else {
                        return false
                    }
                    return this.returnData
                })
            }
            let arr = []
            arr = res.map(item => {
                return {
                    bondId: '', // 主键id
                    changeType: 1,
                    contractId: item.contractId, // 合同id
                    endNotReturnBond: item.endNotReturnBond, // 截止本期末返还保证金
                    id: '',
                    settleId: this.billid, // 结算id
                    returnBond: item.returnBond, // 返还保证金
                    returnBondName: item.returnBondName, // 暂扣保证金名称
                    returnExplain: item.returnExplain // 返还说明
                }
            })
            arr.forEach(item => {
                const isPush = this.returnData.every(
                    i => i.contractId !== item.contractId
                )
                if (isPush) {
                    this.returnData.push(item)
                } else {
                    const newArr = this.returnData.filter(
                        itm => itm.contractId === item.contractId
                    )
                    const indirectPush = newArr.some(m => m.changeType !== -1)
                    if (!indirectPush) {
                        this.returnData.push(item)
                    }
                }
            })
            this.returnData.forEach((item, index) => {
                let isExist = arr.every(it => item.contractId !== it.contractId)
                if (isExist) {
                    if (this.returnData[index]['bondId']) {
                        this.$set(this.returnData[index], 'changeType', -1)
                    }else {
                        this.returnData.splice(index, 1)
                    }
                }
            })
        },
        // 返还保证金/说明内容失去焦点时
        returnBondBlur (row) {
            if (row.changeType === 1) {
                row.changeType = 1
            } else {
                row.changeType = 2
            }
        },
        // 返还保证金单条删除
        returnDelete (row, index) {
            this.clientPop('info', this.oneDeleteErr, () => {
                if (row.bondId) {
                    // 如果有明细id,说明是已经存在后端数据库中的数据,已存在的数据,在删除时只能将changType设为-1
                    this.$set(row, 'changeType', -1)
                } else {
                    // 没有明细id,说明是刚新增的数据,直接在原数组中删除即可
                    this.returnData.splice(index, 1)
                }
            })
        },
        tableRowClassNamefh ({ row }) {
            if (row.changeType === -1) {
                return 'warning-row'
            }
            return ''
        },
        // 复选框选中的数据
        returnSelect (selection) {
            this.returnList = selection.filter(item => item.changeType !== -1)
        },
        // 点击批量删除
        returnClick () {
            const length = this.returnList.length
            if (length === 0) {
                this.clientPop('info', '你还未选择数据,请选择!')
            } else {
                this.clientPop(
                    'info',
                    this.moreDeleteErr(length),
                    this.returnDeleteList
                )
            }
        },
        // 批量删除
        returnDeleteList () {
            this.returnList.filter(row => {
                if (row.bondId) {
                    const index = this.returnData.findIndex(item => {
                        return item.bondId == row.bondId
                    })
                    this.$set(this.returnData[index], 'changeType', -1)
                } else {
                    this.returnData.forEach((item, index) => {
                        if (item.contractId === row.contractId) {
                            this.returnData.splice(index, 1)
                        }
                    })
                }
            })
            this.$refs.returnTable.clearSelection()
        }
    }
}
</script>

<style lang="scss" scoped>
::v-deep.el-table .warning-row {
    display: none;
}
.e-table {
    background: #fff;
}
.mainTitle {
    box-sizing: border-box;
    width: 100%;
    height: 40px;
    line-height: 40px;
    background: rgb(246, 246, 246);
    border: 1px solid rgb(236, 236, 236);
    margin: auto;
    margin-bottom: 15px;
    padding-left: 10px;
}
::v-deep .el-table__fixed{
        height: 100% !important
}
</style>
